<template>
  <div>

    <!-- 1.编辑面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2.定义卡片标签 -->
    <el-card class="box-card">
      <el-row :gutter="10">
        <!-- 2.1 定义用户输入框 -->
        <el-col :span="12">
          <el-input placeholder="按用户名查找" v-model="queryinfo.query" class="input-with-select" clearable
            @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!--  2.2 定义新增用户按钮-->
        <el-col :span="4">
          <el-button type="primary" plain @click="insertUser()">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 定义表格数据
          :data="userList" 表格数据来源 发起Ajax请求，获取后台数据
           prop：从userList中获取的属性值

           stripe：斑马纹效果
       -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="序号">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="phone" label="电话">
        </el-table-column>
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <!--
          要求获取每行的数据记录中的status，布尔类型的值
          scope封装的对象，获取行级元素，row属性
           -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="updateStatus(scope.row)" active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>

        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">
            </el-button>
            <el-button icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--
        3.定义分页功能
        @size-change：当页面的条数变化时触发
        @current-change：当页数改变时触发
        :current-page：当前页数
        :page-sizes：显示页数的数组
        :page-size：初始条件下每页的条数
        layout：显示分页的样式种类，全部显示
        :total：数据的总条数
      -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryinfo.pageNum" :page-sizes="[5, 10, 20, 40]" :page-size="queryinfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    </el-card>

    <el-dialog title="修改已有用户信息" :visible.sync="updateUserDialogVisible">
      <el-form :model="userForm" :rules="rules" ref="userFormRef">
        <el-form-item label="用户名：">
          <el-input v-model="userForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdate()">确 定</el-button>
      </div>
    </el-dialog>

    <!--
    <el-drawer title="新增用户" :before-close="handleClose" :visible.sync="addUserDrawerVisible" direction="ltr"
      custom-class="demo-drawer" ref="drawer" size="50%">
      <div style="margin-right: 100px;">
        <el-form :model="userForm">
          <el-form-item label="用户名：" :label-width="formLabelWidth">
            <el-input v-model="userForm.username" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码：" :label-width="formLabelWidth">
            <el-input v-model="userForm.password" autocomplete="off" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="确认密码：" :label-width="formLabelWidth">
            <el-input autocomplete="off" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="电话：" :label-width="formLabelWidth">
            <el-input v-model="userForm.phone" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" :label-width="formLabelWidth">
            <el-input v-model="userForm.email" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
        <div>
          <el-button style="float: right;" @click="addUserDrawerVisible = false">取 消</el-button>
          <el-button style="float: right;margin-right: 10px;" type="primary" @click="submitInsert()">确 定</el-button>
        </div>
      </div>
    </el-drawer> -->

    <el-dialog title="新增用户" :visible.sync="addUserDialogVisivle" width="70%">

      <el-form :model="addUserForm" :rules="rules" ref="addUserFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="addUserForm.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="addUserForm.password" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="checkPassword">
          <el-input v-model="addUserForm.checkPassword" show-password clearable></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="addUserForm.phone" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="Email:" prop="email">
          <el-input v-model="addUserForm.email" clearable></el-input>
          </el-autocomplete>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addCancel()">取 消</el-button>
        <el-button @click="resetBtn()">重置</el-button>
        <el-button type="primary" @click="submitAdd()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {

      //自定义校验规则，rule：当前规则
      //校验邮箱的规则
      const checkEmail = (rule, value, callback) => {
        //定义邮箱的正则表达式，JS中用/来表示正则表达式的开始和结束
        const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        if (emailRege.test(value)) {
          //表示邮箱合法 正确返回
          return callback()
        }
        callback(new Error('请填写正确的邮箱地址'))
      };

      //校验手机号的规则
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[345789][0-9]{9}$/
        if (phoneRege.test(value)) {

          return callback()
        }
        callback(new Error('请填写正确的手机号'))
      };

      //校验密码的规则
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.addUserForm.checkPassword !== '') {
            this.$refs.addUserFormRef.validateField('checkPassword');
          }
          callback();
        }
      };
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.addUserForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      return {
        //定义分页查询对象
        queryinfo: {
          query: '', //用户查询的数据
          pageNum: 1, //分页查询的页数，默认第一页
          pageSize: 5 //分页查询的条数，初始每页五条
        },
        userList: [], //获取分页后的结果
        total: 0,
        isUpdate: false,
        updateUserDialogVisible: false,
        addUserDrawerVisible: false,
        addUserDialogVisivle: false,
        formLabelWidth: '100px',
        addUserForm: {
          id: '',
          username: '',
          password: '',
          checkPassword: '',
          phone: '',
          email: '',
        },
        userForm: {
          id: '',
          username: '',
          password: '',
          phone: '',
          email: '',
        },
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 12 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            validator: validatePass,
            trigger: 'blur'
          }],
          checkPassword: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            validator: validatePass2,
            trigger: 'blur'
          }],
          phone: [{
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }, {
              validator: checkPhone,
              trigger: 'blur'
            }

          ],
          email: [{
            required: true,
            message: '请输入Email地址',
            trigger: 'blur'
          }, {
            validator: checkEmail,
            trigger: 'blur'
          }]
        }
      }
    },

    methods: {

      addCancel() {
        this.addUserDialogVisivle = false;
        this.$refs.addUserFormRef.resetFields();
      },
      resetBtn() {
        this.$refs.addUserFormRef.resetFields();
      },
      submitAdd() {
        this.$refs.addUserFormRef.validate(async valid => {
          if (!valid) return this.$message.error("数据格式错误!");
          const {
            data: result
          } = await this.$http.post('/user/addUser', this.addUserForm);
          if (result.status !== 200) return this.$message.error(result.msg);

          this.$message.success('用户信息添加成功!');
          this.addUserDialogVisivle = false;
          this.addUserForm = {};
          this.getUserList();
        });
      },

      async submitInsert() {
        const {
          data: result
        } = await this.$http.post('/user/addUser', this.userForm);
        if (result.status !== 200) return this.$message.error(result.msg);

        this.$message.success('用户信息添加成功!');
        this.addUserDrawerVisible = false;
        this.userForm = {};
        this.getUserList();
      },

      submitUpdate() {
        this.$refs.userFormRef.validate(async valid => {
          if (!valid) return this.$message.error("数据格式错误!");
          const {
            data: result
          } = await this.$http.put('/user/updateUser', this.userForm);
          if (result.status !== 200) return this.$message.error(result.msg);
          this.$message.success('用户信息更新成功!');
          this.updateUserDialogVisible = false;
          this.userForm = {};
          this.getUserList();
        });
      },

      async updateStatus(user) {
        console.log(user);
        // 获取用户的ID/状态信息，发起Ajax请求
        // this.$http.put('/user/status' + user.id + '/' + user.status)
        // 模板字符串写法 `` 可以编译多行，可以直接对象取值${key}
        // es6写法
        const {
          data: result
        } = await this.$http.put(`/user/status/${user.id}/${user.status}`);
        if (result.status !== 200) return this.$message.error(result.msg);

        this.$message.success("状态更新成功!");

      },
      async handleDelete(index, row) {

        const result = await this.$confirm('此操作将永久删除' + row.username + ', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error);
        if (result !== 'confirm') return this.$message.info("已取消删除操作!");

        const {
          data: resultDB
        } = await this.$http.delete(`/user/${row.id}`);
        if (resultDB.status !== 200) return this.$message.error(result.msg);
        if ((this.total - 1) % this.queryinfo.pageSize === 0 && this.queryinfo.pageNum !== 1)
          this.queryinfo.pageNum = this.queryinfo.pageNum - 1;
        this.$message.success('用户删除成功!');
        this.getUserList();

      },
      handleEdit(index, row) {
        this.updateUserDialogVisible = true;
        this.userForm = JSON.parse(JSON.stringify(row));
        this.userForm.id = row.id;
      },
      handleSizeChange(pageSize) {
        // 查询的条件需要变化
        this.queryinfo.pageSize = pageSize;
        // 重新查询数据
        this.getUserList();
      },
      handleCurrentChange(pageNum) {
        this.queryinfo.pageNum = pageNum;
        this.getUserList();
      },

      insertUser() {
        this.addUserDrawerVisible = true;
        this.addUserDialogVisivle = true;
      },

      // 动态获取userList数据
      async getUserList() {
        const {
          data: result
        } = await this.$http.get('/user/list', {
          params: this.queryinfo
        });
        if (result.status !== 200) return this.$message.error(result.msg);

        // 为total赋值
        this.total = result.data.total;
        this.userList = result.data.rows;
        console.log(this.total);
        console.log(this.userList);
      }

    },

    // 当页面加载完成之后，调用该函数
    mounted() {
      this.getUserList();
    }
  }
</script>

<!--
  当前样式是否支持less语法 样式的一种语言
  scoped 让样式只对当前组件有效 防止样式击穿
 -->
<style lang="less" scoped>
  .box-card {
    background-image: url(../../assets/background-image.png);
  }
</style>
